﻿using Model;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace Business
{
    public class EmailDataBiz
    {
        public int SaveItem(EmailData item)
        {
            var dbContext = new Context();

            dbContext.EmailDatas.Add(item);
            dbContext.SaveChanges();

            return item.Id;
        }

        public EmailData LoadItem(int id)
        {
            var dbContext = new Context();
            return (from item in dbContext.EmailDatas
                    where item.Id == id
                    select item).First();
        }

        public void RemoveItem(List<EmailData> items)
        {
            var dbContext = new Context();

            string ids = string.Empty;

            foreach (var item in items)
            {
                ids += item.Id + ",";
            }

            if (ids.EndsWith(","))
            {
                ids = ids.Substring(0, ids.Length-1);

                string deleteCommand = string.Format(Constants.DeleteCommand, "EmailData", ids);
                dbContext.Database.ExecuteSqlCommand(deleteCommand);
            }            
        }

        public List<EmailData> LoadItems()
        {
            var dbContext = new Context();
            return (from item in dbContext.EmailDatas
                    orderby item.SendOn descending
                    select item).ToList();
        }
    }
}
